import { win32, posix } from 'path';

export interface Options {
  root: string;
}

export interface Plugin {
  name: string;
  transform: (code: string, id: string) => string;
}

function normalizePath(filename: string): string {
  return filename.split(win32.sep).join(posix.sep);
}

export default function ReplaceSourcemapUrlPlugin(options: Options): Plugin {
  return {
    name: 'vite-plugin-replace-sourcemap-url',
    transform(code: string, id: string) {
      id = normalizePath(id);
      const root = normalizePath(options.root);
      const paths = id.split('/');
      const fileName = paths[paths.length - 1];
      const reg1 = new RegExp(`\/\\*# sourceMappingURL=${fileName}.map\\*\/`, 'g');
      const reg2 = new RegExp(`\/\/# sourceMappingURL=${fileName}.map`, 'g');
      return code
        .replace(reg1, `/*# sourceMappingURL=${id.replace(root, '')}.map*/`)
        .replace(reg2, `//# sourceMappingURL=${id.replace(root, '')}.map`);
    },
  };
}
